import type { QRL } from "@builder.io/qwik";
import { $, useStore, useTask$, useVisibleTask$ } from "@builder.io/qwik";
import type { IMenu, IMenuState } from "./types";
import type { IMenuItem } from "../MenuItem/types";


export function useState(props: IMenu): [IMenuState, QRL<(value: Partial<IMenuState>) => void>] {


    const state = useStore<IMenuState>({
        duration: 300,
        activeKey: undefined,
        onHanlder: $(() => { }),
    });



    const setStore = $((value: Partial<IMenuState>) => {
        Object.assign(state, value)
    })

    const onHanlder = $((item: IMenuItem) => {
        if (!item.tabKey) return;
        const { onMenuHanlder } = props;
        if (onMenuHanlder) onMenuHanlder(item)
        else {
            setStore({ activeKey: item.tabKey })
        }
    })

    useTask$(() => {
        state.onHanlder = onHanlder
    })

    useVisibleTask$(({ track }) => {
        track(() => props.activeKey)
        track(() => props.duration)
        setStore(props)
    })

    return [state, setStore]
}